package com.xyxy.platform.modules.service.sns.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyxy.platform.modules.entity.sns.MemberCollection;
import com.xyxy.platform.modules.entity.sns.MemberCollectionExample;
import com.xyxy.platform.modules.repository.mybatis.sns.MemberCollectionMapper;
import com.xyxy.platform.modules.service.sns.CollectionService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 获取会员服务收藏列表、添加或取消收藏
 *
 * @author liushun
 * @version 1.0
 * @Date 2015-12-21
 */
@Service
@Transactional(readOnly = true)
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private MemberCollectionMapper memberCollectionMapper;

    /**
     * 获取会员服务收藏列表
     *
     * @param memberId   会员ID
     * @param pageNumber 当前页数
     * @param pageSize   每页大小
     * @return
     */
    @Override
    public PageInfo getCollectionPage(Long memberId, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List list = memberCollectionMapper.selectGoodsPage(memberId);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 添加收藏
     *
     * @param memberCollection 会员收藏夹实体类
     * @return
     */
    @Override
    public int createCollection(MemberCollection memberCollection) {
        /*根据被会员ID和商品ID查询是否已收藏过*/
        int flag = memberCollectionMapper.selectIsGoodsCollection(memberCollection.getMemberId(), memberCollection.getGoodsid());
        if (flag > 0)
            return 0;
        else {
            int result = memberCollectionMapper.insert(memberCollection);
            //TODO 调用 DAO 把操作添加到会员关注日志表
            return result;
        }
    }

    /**
     * 取消收藏
     *
     * @param collectionId 收藏ID
     * @param memberId     会员ID
     * @return
     */
    @Override
    public int deleteCollection(Long collectionId, Long memberId) {
        return memberCollectionMapper.deleteByPrimaryKey(collectionId);
    }

    @Override
    public int selectCountByGoodsId(long goodsId) {
        MemberCollectionExample memberCollectionExample = new MemberCollectionExample();
        memberCollectionExample.or().andGoodsidEqualTo(goodsId);
        return memberCollectionMapper.countByExample(memberCollectionExample);
    }

    @Override
    public boolean isCollection(Long memberId, Long goodsId) {
        MemberCollectionExample sql = new MemberCollectionExample();
        sql.or().andMemberIdEqualTo(memberId).andGoodsidEqualTo(goodsId);
        int count = memberCollectionMapper.countByExample(sql);
        return count > 0;
    }

}
